package com.gx.smart.building.ui.inspection.fragment

import android.content.Intent
import android.view.ViewGroup
import com.gx.smart.base.BaseAdapter
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentInspectionInCompleteBinding
import com.gx.smart.building.ui.inspection.InspectionDetailActivity
import com.gx.smart.building.ui.inspection.adapter.InspectionRecordAdapter
import com.gx.smart.building.ui.inspection.event.InspectionListEvent
import com.gx.smart.building.ui.inspection.event.TaskInCompleteEvent
import com.gx.smart.lib.http.api.response.PlanTask
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskDto
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class InspectionInCompleteFragment : CommonFragment(),
    BaseAdapter.OnItemClickListener<PlanTask> {
    private lateinit var viewBinding: FragmentInspectionInCompleteBinding
    private lateinit var adapter: InspectionRecordAdapter
    private var list: List<PlanTaskDto>? = null
    override fun onItemClick(e: PlanTask, position: Int) {
        val intent = Intent(requireActivity(), InspectionDetailActivity::class.java)
        intent.putExtra("id", e.id)
        intent.putExtra("position", 0)
        startActivity(intent)
        EventBus.getDefault().postSticky(TaskInCompleteEvent(e))
    }

    override fun onBindLayout(): Int = R.layout.fragment_inspection_in_complete


    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentInspectionInCompleteBinding.inflate(layoutInflater, root, true)
    }

    override fun initContent() {
        super.initContent()
        adapter = InspectionRecordAdapter(activity)
        adapter.setItemClickListener(this)
        initView(viewBinding.recyclerView, adapter, viewBinding.refreshLayout)
    }

    override fun doAction() {
        viewModel.queryPlanTaskList(currentPage, 2, keyword ?: "", 0, 0)
            .observe(viewLifecycleOwner) {
                handleResult(it)
            }
    }

    override fun search(keyword: String?) {
        super.search(keyword)
        viewBinding.refreshLayout.autoRefresh()
    }

    override fun onResume() {
        super.onResume()
        viewBinding.refreshLayout.autoRefresh()
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun handleEvent(event: InspectionListEvent) {
        list = event.list
    }

    override fun initData() {
        super.initData()
        registerEventBus()
        handleResult(list)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterEventBus()
    }


    companion object {
        @JvmStatic
        fun newInstance() =
            InspectionInCompleteFragment()
    }
}